package com.zhkj.txg.module.login.vm

import android.app.Application
import android.os.CountDownTimer
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseApplication
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.ToastUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.login.entity.LoginResponse
import com.zhkj.txg.module.login.entity.SendCodeResponse
import com.zhkj.txg.module.login.entity.ThirdLoginResponse
import com.zhkj.txg.module.login.entity.UserAgreementResponse
import com.zhkj.txg.module.login.model.LOGIN
import com.zhkj.txg.module.login.model.LoginManager
import com.zhkj.txg.module.login.ui.LoginActivity
import com.zhkj.txg.utils.ThirdLoginEvent
import io.reactivex.android.schedulers.AndroidSchedulers

class LoginViewModel(application: Application) : BaseViewModel(application) {
    private val loginManager = LoginManager()
    private var timer: CountDownTimer? = null

    private val thirdLoginResultLiveData = MutableLiveData<ThirdLoginEvent>()
    private val sendCodeLiveData = MutableLiveData<HttpResponse<SendCodeResponse>>()
    private val loginLiveData = MutableLiveData<HttpResponse<LoginResponse>>()
    private val bindInviteLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    private val userAgreementLiveData = MutableLiveData<HttpResponse<UserAgreementResponse>>()
    val pageIndexLiveData: MutableLiveData<LoginActivity.Index> = MutableLiveData()
    val countDownLiveData: MutableLiveData<Int> = MutableLiveData()
    val thirdLoginLiveData = MutableLiveData<HttpResponse<ThirdLoginResponse>>()

    // 获取验证码的手机号
    var mobile2GetCode: String = ""
        private set

    // 判断手机号码是新注册或者登录
    var mobileIsNewUser: Boolean = false

    override fun onCleared() {
        super.onCleared()
        if (timer != null) timer?.cancel()
    }

    fun sendCode(mobile: String): MutableLiveData<HttpResponse<SendCodeResponse>> {
        if (isMobileValid(mobile)) {
            val listener = object : ViewModelSubscribeListener<SendCodeResponse>(sendCodeLiveData) {
                override fun onSuccess(resp: SendCodeResponse) {
                    super.onSuccess(resp)
                    // 记录数据
                    mobile2GetCode = mobile
                    mobileIsNewUser = resp.data.newUser
                    // 页面跳转
                    pageIndexLiveData.value = LoginActivity.Index.CAPTCHA
                    // 倒计时
                    startCountDown()
                }
            }
            dispose.add(loginManager.sendCode(mobile, LOGIN, listener))
        }
        return sendCodeLiveData
    }

    fun login(captcha: String): MutableLiveData<HttpResponse<LoginResponse>> {
        if (isMobileValid(mobile2GetCode)) {
            val listener = object : ViewModelSubscribeListener<LoginResponse>(loginLiveData) {
                override fun onSuccess(resp: LoginResponse) {
                    super.onSuccess(resp)
                    AccountManager.saveToken(resp.data.userInfo.token)
                    AccountManager.saveUserId(resp.data.userInfo.user_id.toLong())
                    AccountManager.saveNickname(resp.data.userInfo.nickname)
                    AccountManager.saveAvatar(resp.data.userInfo.avatar)
                    AccountManager.saveMemberStatus(resp.data.isMember)
                    if (resp.data.isNew) {
                        // 记录数据
                        mobileIsNewUser = true
                        // 页面跳转
                        pageIndexLiveData.value = LoginActivity.Index.INVITE
                    } else {
                        // 记录数据
                        mobileIsNewUser = false
                        // 页面跳转
                        pageIndexLiveData.value = LoginActivity.Index.HOME
                    }
                }
            }
            dispose.add(loginManager.mobileLogin(mobile2GetCode, captcha, listener))
        }
        return loginLiveData
    }

    fun userAgreement(): MutableLiveData<HttpResponse<UserAgreementResponse>> {
        val listener = ViewModelSubscribeListener(userAgreementLiveData)
        dispose.add(loginManager.userAgreement(listener))
        return userAgreementLiveData
    }

    fun bindInvite(token: String, code: String): MutableLiveData<HttpResponse<BaseResponse>> {
        val listener = object : ViewModelSubscribeListener<BaseResponse>(bindInviteLiveData) {
            override fun onSuccess(resp: BaseResponse) {
                super.onSuccess(resp)
                pageIndexLiveData.value = LoginActivity.Index.REGISTER
            }
        }
        dispose.add(loginManager.bindInvite(token, code, listener))
        return bindInviteLiveData
    }

    fun thirdLogin(platform: String, code: String) {
        val listener = object : ViewModelSubscribeListener<ThirdLoginResponse>(thirdLoginLiveData) {
            override fun onSuccess(resp: ThirdLoginResponse) {
                resp.data?.userInfo?.let {
                    // 将用户昵称和用户头像保存起来，在此处保存，不用担心数据错乱
                    AccountManager.saveNickname(it.nickname)
                    AccountManager.saveAvatar(it.avatar)
                    AccountManager.saveMemberStatus(resp.data.isMember)
                }
                super.onSuccess(resp)
            }
        }
        val thirdLogin = loginManager.thirdLogin(platform, code, listener)
        dispose.add(thirdLogin)
    }

    fun thirdLoginResultSubscribe(): MutableLiveData<ThirdLoginEvent> {
        val subscribe = RxBus.toObservable(ThirdLoginEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ thirdLoginResultLiveData.value = it }, { it.printStackTrace() })
        dispose.add(subscribe)
        return thirdLoginResultLiveData
    }

    private fun startCountDown() {
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        timer = object : CountDownTimer(60 * 1000, 1000) {
            override fun onFinish() {
                countDownLiveData.value = 0
            }

            override fun onTick(millisUntilFinished: Long) {
                countDownLiveData.value = (millisUntilFinished / 1000).toInt()
            }
        }
        timer?.start()
    }

    private fun isMobileValid(mobile: String): Boolean {
        val telRegex = "[1]\\d{10}"
        if (TextUtils.isEmpty(mobile) || !mobile.matches(Regex(telRegex))) {
            ToastUtil.show(BaseApplication.INSTANCE.resources.getString(R.string.wrong_mobile))
            return false
        }
        return true
    }
}